package irisext

import (
	"fmt"
	"runtime"

	"gitee.com/terender/sfw/rlog"

	"github.com/kataras/iris/v12"
)

// New returns a new recover middleware,
// it recovers from panics and logs
// the panic message to the application's logger "Warn" level.
func New() iris.Handler {
	return func(ctx iris.Context) {
		defer func() {
			if err := recover(); err != nil {
				if ctx.IsStopped() {
					return
				}
				var stacktrace string
				for i := 1; ; i++ {
					_, f, l, got := runtime.Caller(i)
					if !got {
						break
					}
					stacktrace += fmt.Sprintf("%s:%d\n", f, l)
				}
				// when stack finishes
				logMessage := fmt.Sprintf("Recovered from a route's Handler('%s')\n", ctx.HandlerName())
				logMessage += fmt.Sprintf("At Request: %s\n", string(cachedBody(ctx)))
				logMessage += fmt.Sprintf("Trace: %s\n", err)
				logMessage += fmt.Sprintf("\n%s", stacktrace)
				rlog.Errorf(logMessage)
				//ctx.Application().Logger().Warn(logMessage)
				E(ctx, 500, logMessage)
				//ctx.StatusCode(500)
				ctx.StopExecution()
			}
		}()
		ctx.Next()
	}
}
